/*
 * Copyright (c) 2017,重庆阿莫比科技有限公司,All Rights Reserved.
 */
package com.wowocai.btchina.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GzipRequestFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request_ = (HttpServletRequest) request;
        HttpServletResponse response_ = (HttpServletResponse) response;
        if (supportsGzip(request)) {
            GzipRequestWrapper gzipRequest = new GzipRequestWrapper(request_);
            chain.doFilter(gzipRequest, response_);
        } else {
            chain.doFilter(request_, response_);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    private boolean supportsGzip(ServletRequest request) {
        String acceptEncoding = ((HttpServletRequest) request).getHeader("Content-Encoding");
        return acceptEncoding != null && acceptEncoding.contains("gzip");
    }

}
